package com.example.springaiaibaba1;

import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/ai")
public class AIChatController {

    private final WebClient webClient;
    private final String API_KEY = "sk-16de000f4a0b45a9918c45844dfa7f66";
    private final String API_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions";

    public AIChatController() {
        this.webClient = WebClient.builder()
                .baseUrl(API_URL)
                .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                .defaultHeader("Authorization", "Bearer " + API_KEY)
                .build();
    }

    @GetMapping("/chat")
    public Mono<String> chat(@RequestParam String message) {
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", "qwen-turbo");

        Map<String, Object> messageMap = new HashMap<>();
        messageMap.put("role", "user");
        messageMap.put("content", message);

        requestBody.put("messages", new Object[]{messageMap});
        requestBody.put("stream", false);

        return webClient.post()
                .bodyValue(requestBody)
                .retrieve()
                .bodyToMono(Map.class)
                .map(response -> {
                    // 解析响应
                    Map<String, Object> choices = (Map<String, Object>) ((java.util.List) response.get("choices")).get(0);
                    Map<String, Object> messageResponse = (Map<String, Object>) choices.get("message");
                    return (String) messageResponse.get("content");
                });
    }

    @GetMapping("/hello")
    public String hello() {
        return "AI 服务手动实现版本正常运行！";
    }
}